import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _isEmpty from "lodash/isEmpty";
import _isUndefined from "lodash/isUndefined";

/**
 *  数据权限维度动态渲染 __组件
 * @date: 2019-9-11
 */
import { connect } from 'dva';
import React, { useEffect, useRef, useState } from 'react';
import { Button, Form, Input, message, Modal, Switch, Table, Tooltip, Row, Col } from 'antd';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import notification from 'utils/notification';
import { createPagination } from 'utils/utils';
import { SEARCH_FORM_ITEM_LAYOUT } from 'utils/constants';
import { queryLov } from 'services/api';
import AddDataModal from "./AddDataModal";

function AuthorityTab(props) {
  var dataSourceRef = useRef(null);

  var _useState = useState([]),
      _useState2 = _slicedToArray(_useState, 2),
      selectRows = _useState2[0],
      setSelectRows = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      addModalVisible = _useState4[0],
      setAddModalVisible = _useState4[1];

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      switchLoading = _useState6[0],
      setSwitchLoading = _useState6[1];

  var _useState7 = useState([]),
      _useState8 = _slicedToArray(_useState7, 2),
      list = _useState8[0],
      setList = _useState8[1];

  var _useState9 = useState({}),
      _useState10 = _slicedToArray(_useState9, 2),
      head = _useState10[0],
      setHead = _useState10[1];

  var _useState11 = useState({}),
      _useState12 = _slicedToArray(_useState11, 2),
      pagination = _useState12[0],
      setPagination = _useState12[1];

  var _useState13 = useState({}),
      _useState14 = _slicedToArray(_useState13, 2),
      lov = _useState14[0],
      setLov = _useState14[1];

  var _useState15 = useState(false),
      _useState16 = _slicedToArray(_useState15, 2),
      lovModal = _useState16[0],
      setLovModal = _useState16[1];

  var form = props.form,
      code = props.code,
      name = props.name,
      _props$tenantId = props.tenantId,
      tenantId = _props$tenantId === void 0 ? undefined : _props$tenantId,
      dispatch = props.dispatch,
      queryParams = props.queryParams,
      authorityTypeCode = props.authorityTypeCode,
      addLoading = props.addLoading,
      fetchLoading = props.fetchLoading,
      _props$isSecGrp = props.isSecGrp,
      isSecGrp = _props$isSecGrp === void 0 ? false : _props$isSecGrp,
      _props$isAccount = props.isAccount,
      isAccount = _props$isAccount === void 0 ? false : _props$isAccount;
  var columns = [{
    title: intl.get('ciam.authorityManagement.model.authorityManagement.name', {
      name: name
    }).d("".concat(name, "\u540D\u79F0")),
    dataIndex: 'dataName'
  }];
  /**
   *查询数据
   *
   * @param {Object} pageData
   */

  var fetchData = function fetchData() {
    var pageData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    form.validateFields(function (err, fieldsValue) {
      if (!err) {
        var payload = _objectSpread(_objectSpread(_objectSpread({
          authorityTypeCode: authorityTypeCode
        }, fieldsValue), queryParams), pageData);

        if (isSecGrp) {
          if (!isAccount) {
            dispatch({
              type: "authorityDimension/querySecGrpAuthorityData",
              payload: payload
            }).then(function (res) {
              if (res) {
                setList(res.content);
                setPagination(createPagination(res));
              }
            });
          } else {
            dispatch({
              type: "authorityDimension/queryAccountSecGrpAuthorityData",
              payload: payload
            }).then(function (res) {
              if (res) {
                setList(res.content);
                setPagination(createPagination(res));
              }
            });
          }
        } else {
          dispatch({
            type: "authorityDimension/query".concat(!_isUndefined(queryParams.userId) ? "User" : "Role", "AuthorityData"),
            payload: payload
          }).then(function (res) {
            if (res) {
              setHead(res.userAuthority || res.roleAuthData);
              setList(res.userAuthorityLineList ? res.userAuthorityLineList.content : res.roleAuthDataLineList.content);
              setPagination(createPagination(res.userAuthorityLineList || res.roleAuthDataLineList));
            }
          });
        }
      }
    });
  };

  useEffect(function () {
    queryLov({
      viewCode: code
    }).then(function (res) {
      var lovInfo = _objectSpread({}, res);

      if (!_isEmpty(lovInfo)) {
        var hasCode = lovInfo.viewCode;

        if (hasCode) {
          setLov(lovInfo);
        } else {
          message.error(intl.get('cpaas.common.components.lov.notification.undefined').d('值集视图未定义!'));
          setLovModal(true);
        }
      }
    });
    fetchData();
  }, []);
  /**
   * 添加数据
   * @param {Array} addRows 选择的数据
   */

  var addData = function addData(addRows) {
    dispatch({
      type: "authorityDimension/add".concat(!_isUndefined(queryParams.userId) ? "User" : "Role", "AuthorityData"),
      payload: _objectSpread(_objectSpread({}, queryParams), {}, {
        authorityTypeCode: authorityTypeCode,
        authData: head,
        authDataLineList: addRows
      })
    }).then(function (response) {
      if (response) {
        onHideAddModal();
        notification.success();
        refresh();
      }
    });
  };
  /**
   *删除方法
   */


  var remove = function remove() {
    var onOk = function onOk() {
      dispatch({
        type: "authorityDimension/delete".concat(!_isUndefined(queryParams.userId) ? "User" : "Role", "AuthorityData"),
        payload: _objectSpread(_objectSpread({}, queryParams), {}, {
          deleteRows: selectRows
        })
      }).then(function (response) {
        if (response) {
          refresh();
          notification.success();
        }
      });
    };

    Modal.confirm({
      title: intl.get('cpaas.common.message.confirm.remove').d('确定删除选中数据？'),
      onOk: onOk
    });
  };
  /**
   *刷新
   */


  var refresh = function refresh() {
    fetchData();
    setSelectRows([]);
  };
  /**
   * 表格勾选
   * @param {null} _ 占位
   * @param {object} selectedRow 选中行
   */


  var onSelectChange = function onSelectChange(_, selectedRows) {
    setSelectRows(selectedRows);
  };

  var rowSelection = isSecGrp ? null : {
    onChange: onSelectChange,
    selectedRowKeys: selectRows.map(function (n) {
      return n.dataId;
    })
  };
  /**
   * 展示弹出框
   */

  var onShowAddModal = function onShowAddModal() {
    if (!lovModal) {
      setAddModalVisible(true);
    } else {
      message.error(intl.get('cpaas.common.components.lov.notification.undefined').d('值集视图未定义!'));
    }
  };
  /**
   * 隐藏弹出框
   */


  var onHideAddModal = function onHideAddModal() {
    dataSourceRef.current.state.addRows = [];
    setAddModalVisible(false);
  };
  /**
   *点击查询按钮事件
   */


  var queryValue = function queryValue() {
    fetchData();
    setSelectRows([]);
  };
  /**
   *分页change事件
   */


  var handleTableChange = function handleTableChange() {
    var page = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
    fetchData({
      page: page
    });
  };
  /**
   * 表单重置
   */


  var handleFormReset = function handleFormReset() {
    form.resetFields();
  };
  /**
   *点击加入全部后触发事件
   *
   * @param {Boolean} checked switch的value值
   */


  var includeAllFlag = function includeAllFlag(checked) {
    setSwitchLoading(true);
    dispatch({
      type: "authorityDimension/add".concat(!_isUndefined(queryParams.userId) ? "User" : "Role", "AuthorityData"),
      payload: _objectSpread(_objectSpread({}, queryParams), {}, {
        authorityTypeCode: authorityTypeCode,
        authData: _objectSpread(_objectSpread({}, head), {}, {
          includeAllFlag: checked ? 1 : 0
        }),
        authDataLineList: []
      })
    }).then(function (response) {
      if (response) {
        refresh();
        notification.success();
        setSwitchLoading(false);
      }
    });
  };

  var addModalOptions = {
    rowKey: 'dataId',
    title: intl.get('ciam.authorityManagement.model.authorityManagement.select', {
      name: name
    }).d("\u9009\u62E9".concat(name)),
    lov: lov,
    tenantId: tenantId,
    confirmLoading: addLoading,
    modalVisible: addModalVisible,
    onShowAddModal: onShowAddModal,
    onHideAddModal: onHideAddModal,
    addData: addData,
    ref: dataSourceRef
  };
  /**
   *渲染查询结构
   *
   * @returns
   */

  var renderForm = function renderForm() {
    return /*#__PURE__*/React.createElement(Form, null, /*#__PURE__*/React.createElement(Row, {
      type: "flex",
      gutter: 24,
      align: "bottom"
    }, /*#__PURE__*/React.createElement(Col, {
      span: 12
    }, /*#__PURE__*/React.createElement(Form.Item, Object.assign({}, SEARCH_FORM_ITEM_LAYOUT, {
      label: intl.get('ciam.authorityManagement.model.authorityManagement.name', {
        name: name
      }).d("".concat(name, "\u540D\u79F0"))
    }), form.getFieldDecorator('dataName')( /*#__PURE__*/React.createElement(Input, null)))), /*#__PURE__*/React.createElement(Col, {
      span: 12
    }, /*#__PURE__*/React.createElement(Form.Item, SEARCH_FORM_ITEM_LAYOUT, /*#__PURE__*/React.createElement(Button, {
      style: {
        marginRight: 8
      },
      onClick: handleFormReset
    }, intl.get('cpaas.common.button.reset').d('重置')), /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      onClick: function onClick() {
        return queryValue();
      },
      htmlType: "submit"
    }, intl.get('cpaas.common.button.search').d('查询'))))));
  };
  /**
   *渲染查询结构
   *
   * @returns
   */
  // const renderColumns = () => {
  //   // return (
  //   // );
  // };


  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    className: "table-list-search"
  }, renderForm()), !isSecGrp && /*#__PURE__*/React.createElement("div", {
    style: {
      textAlign: 'right'
    }
  }, !head.includeAllFlag && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Button, {
    style: {
      margin: '0 8px 16px 0'
    },
    onClick: function onClick() {
      return onShowAddModal();
    }
  }, intl.get('ciam.authorityManagement.model.authorityManagement.create', {
    name: name
  }).d("\u65B0\u5EFA".concat(name, "\u6743\u9650"))), /*#__PURE__*/React.createElement(Button, {
    style: {
      margin: '0 8px 16px 0'
    },
    disabled: selectRows.length <= 0,
    onClick: function onClick() {
      return remove();
    }
  }, intl.get('ciam.authorityManagement.model.authorityManagement.delete', {
    name: name
  }).d("\u5220\u9664".concat(name, "\u6743\u9650")))), /*#__PURE__*/React.createElement("div", {
    style: {
      display: 'inline-block',
      margin: '0 8px 16px 0'
    }
  }, /*#__PURE__*/React.createElement("span", {
    style: {
      marginRight: '8px'
    }
  }, intl.get('ciam.authority.view.message.label').d('加入全部:')), /*#__PURE__*/React.createElement(Tooltip, {
    title: intl.get('ciam.authorityManagement.view.message.title.tooltip.dg').d('“加入全部”即将所有数据组权限自动添加至当前账户，无需再手工添加。'),
    placement: "right"
  }, /*#__PURE__*/React.createElement(Switch, {
    loading: switchLoading || fetchLoading,
    checked: !!head.includeAllFlag,
    onChange: includeAllFlag
  })))), /*#__PURE__*/React.createElement(Table, {
    bordered: true,
    rowKey: "dataId",
    dataSource: list,
    columns: columns,
    loading: fetchLoading,
    pagination: pagination,
    rowSelection: rowSelection,
    onChange: handleTableChange
  }), /*#__PURE__*/React.createElement(AddDataModal, addModalOptions));
}

function mapStateToProps(_ref) {
  var authorityDimension = _ref.authorityDimension,
      loading = _ref.loading;
  return {
    authorityDimension: authorityDimension,
    addLoading: loading.effects["authorityDimension/addUserAuthorityData"] || loading.effects["authorityDimension/addRoleAuthorityData"],
    fetchLoading: loading.effects["authorityDimension/queryUserAuthorityData"] || loading.effects["authorityDimension/queryRoleAuthorityData"] || loading.effects["authorityDimension/querySecGrpAuthorityData"] || loading.effects["authorityDimension/queryAccountSecGrpAuthorityData"]
  };
}

function mapDispatchToProps(dispatch) {
  return {
    dispatch: dispatch
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Form.create({
  fieldNameProp: null
})(formatterCollections({
  code: ['ciam.authorityManagement', 'entity.tag']
})(AuthorityTab)));